<template>
  <div class="customer-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="customer-search">
        <el-form ref="searchFormRef" :model="searchForm" inline>
          <el-form-item label="客户" prop="customer_id">
            <CustomerSelect v-model="searchForm.customer_id"> </CustomerSelect>
          </el-form-item>
          <el-form-item label="供应商" prop="supplier_id">
            <SupplierSelect v-model="searchForm.supplier_id"> </SupplierSelect>
          </el-form-item>
          <el-form-item label="项目经理" prop="manager_id">
            <UserSelect
              v-model="searchForm.manager_id"
              :work-role="WorkRole.MANAGER"
            ></UserSelect>
          </el-form-item>
          <el-form-item label="设计师" prop="designer_id">
            <UserSelect
              v-model="searchForm.designer_id"
              :work-role="WorkRole.DESIGNER"
            ></UserSelect>
          </el-form-item>
          <el-form-item label="收款状态" prop="receive_status">
            <CustomerSelect
              v-model="searchForm.receive_status"
              clearable
              :options="receiveStatusOptions"
            ></CustomerSelect>
          </el-form-item>
          <el-form-item label="经办人" prop="contact_name">
            <el-input v-model="searchForm.contact_name"></el-input>
          </el-form-item>
          <el-form-item label="所属部门" prop="customer_dept">
            <el-input v-model="searchForm.customer_dept"></el-input>
          </el-form-item>
          <!-- <el-form-item label="付款状态" prop="pay_status">
            <CustomerSelect
              v-model="searchForm.pay_status"
              clearable
              :options="payStatusOptions"
            ></CustomerSelect>
          </el-form-item> -->
          <el-form-item label="项目创建时间" prop="date">
            <ElDatePicker
              v-model="searchForm.date"
              type="daterange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            ></ElDatePicker>
          </el-form-item>
          <el-form-item>
            <el-button size="default" type="primary" @click="refresh">
              <el-icon>
                <ele-Search />
              </el-icon>
              查询
            </el-button>
            <el-button size="default" @click="onRest">
              <el-icon>
                <ele-RefreshRight />
              </el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-tool-bar mb15">
        <el-button size="default" type="primary" @click="handleExport()">
          导出
        </el-button>
      </div>
      <el-table
        :data="tableData.list"
        v-loading="loading"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="project.customer.name" label="客户">
        </el-table-column>
        <el-table-column prop="name" label="产品名称"> </el-table-column>
        <el-table-column prop="size" label="规格型号"> </el-table-column>
        <el-table-column prop="material" label="工艺材质"> </el-table-column>
        <el-table-column prop="unit" label="单位"> </el-table-column>
        <el-table-column prop="num" label="数量"> </el-table-column>
        <el-table-column prop="unit_price" label="单价（元）">
        </el-table-column>
        <el-table-column prop="total_price" label="总价（元）">
        </el-table-column>
        <el-table-column label="供应商">
          <template v-slot="{ row }">
            {{ getSupplierNames(row) }}
          </template>
        </el-table-column>
        <el-table-column label="附件">
          <template v-slot="{ row }">
            <el-button
              v-if="row.files && row.files !== '[]'"
              type="text"
              @click="handleViewFiles(row)"
              >查看附件</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="project.contact_name" label="经办人">
        </el-table-column>
        <el-table-column prop="remark" label="备注"> </el-table-column>
        <el-table-column label="项目创建时间" width="160">
          <template v-slot="{ row }">
            {{ formatDate(row.project?.created_at, 'time') }}
          </template>
        </el-table-column>
      </el-table>
      <CommonPagination
        :pagination="pagination"
        :total="tableData.total"
      ></CommonPagination>
    </el-card>
    <ViewFilesDialog ref="viewFilesDialogRef"></ViewFilesDialog>
    <ExportDialog ref="exportDialogRef" @confirm="exportData" />
  </div>
</template>

<script setup lang="ts" name="customer">
import { reactive, ref, onMounted } from 'vue';
import { FormInstance, ElLoading } from 'element-plus';
import { useTable } from '/@/hooks/use-table';
import CommonPagination from '/@/components/common-pagination/index.vue';
import CustomerSelect from '/@/components/customer-select/index.vue';
import SupplierSelect from '/@/components/supplier-select/index.vue';
import { readAllProducts, exportProducts } from '/@/api/product';
import ViewFilesDialog from '/@/components/view-files-dialog/index.vue';
import UserSelect from '/@/components/user-select/index.vue';
import { formatDate } from '/@/utils';
import {
  WorkRole,
  ReceiveStatus,
  ReceiveStatusLabel,
  PayStatus,
  PayStatusLabel
} from '/@/constants';
import { readAllSupplier } from '/@/api/supplier';
import { readAllCustomer } from '/@/api/customer';
import { saveAs } from 'file-saver';
import ExportDialog from './components/export-dialog.vue';
import dayjs from 'dayjs';

const viewFilesDialogRef = ref();
const exportDialogRef = ref();

const searchFormRef = ref<FormInstance>();
const searchForm = reactive({
  customer_id: undefined,
  supplier_id: undefined,
  manager_id: undefined,
  designer_id: undefined,
  receive_status: undefined,
  pay_status: undefined,
  contact_name: undefined,
  customer_dept: undefined,
  date: []
});
const customerList = ref([]);
const supplierList = ref([]);

const receiveStatusOptions = [
  {
    label: ReceiveStatusLabel.WAIT_RECEIVE,
    value: ReceiveStatus.WAIT_RECEIVE
  },
  {
    label: ReceiveStatusLabel.TICKETED,
    value: ReceiveStatus.TICKETED
  },
  {
    label: ReceiveStatusLabel.COMPLETED,
    value: ReceiveStatus.COMPLETED
  }
];

const payStatusOptions = [
  {
    label: PayStatusLabel.WAIT_PAY,
    value: PayStatus.WAIT_PAY
  },
  {
    label: PayStatusLabel.COMPLETED,
    value: PayStatus.COMPLETED
  }
];

const { tableData, loading, pagination, refresh } = useTable<any>(
  ({ page, pageSize }) => {
    const params: any = {
      page,
      pageSize,
      sortType: 'asc',
      sortProp: 'created_at',
      ...searchForm
    };
    delete params.date;
    if (searchForm.date) {
      params['project_start_date'] = searchForm.date[0];
      params['project_end_date'] = searchForm.date[1];
    }
    return readAllProducts(params).then(({ data }) => {
      return {
        total: data?.total,
        list: data?.list
      };
    });
  }
);

const onRest = () => {
  searchFormRef.value?.resetFields();
  refresh();
};

const handleViewFiles = (row: any) => {
  const files = row.files ? JSON.parse(row?.files) : [];
  viewFilesDialogRef.value?.openDialog(files);
};

onMounted(() => {
  readAllSupplier().then(({ data }) => {
    supplierList.value = data.list;
  });
  readAllCustomer().then(({ data }) => {
    customerList.value = data.list;
  });
});

const handleExport = () => {
  exportDialogRef.value.openDialog();
};

const getSupplierNames = (row: any) => {
  console.log('row', row);
  return (row.MakeWork || [])
    .map((item: any) => item?.supplier?.name || '')
    .join(',');
};

const exportData = async (fields: string[]) => {
  const loading = ElLoading.service({ fullscreen: true, text: '导出中' });
  try {
    const params: any = { ...searchForm, fields };
    delete params.date;
    if (searchForm.date) {
      params['start_date'] = searchForm.date[0];
      params['end_date'] = searchForm.date[1];
    }
    const res = await exportProducts(params);
    saveAs(res, '产品制作清单-' + dayjs().format('YYYYMMDD'));
  } catch (err) {
    console.log(err);
  }
  loading.close();
};
</script>

<style scoped lang="scss">
.customer-container {
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: auto;
    .el-table {
      flex: 1;
    }
  }
}
</style>
